import React, { Component } from 'react';
import {
  Text,
  View,
  StyleSheet,
  Image,
  TextInput,
  TouchableOpacity,
  Keyboard,
  FlatList,
  ActivityIndicator,
  RefreshControl,
  ImageBackground
} from 'react-native';

import NavBar from '../../components/PublicHeader';
import { Images } from '../../public/images/images';
import { Constant } from '../../public/js/constant';
import fetchWebApi from '../../public/WebApi/fetchBase';
import { GET_USER_MAILLIST, GET_USER_NEWFRIENDS, GET_USER_USERINFO } from '../../public/WebApi/mailListApi';
import getStorageValue from '../../utils/getStorageValue';
import pinyin, { STYLE_FIRST_LETTER } from 'pinyin';
import AsyncStorage from '@react-native-community/async-storage';
import Loading from '../../components/Loading';

export default class maillist extends Component {
  constructor(props) {
    super(props);
    this.state = {
      sections: [],
      DATA: [],
      arr: [],
      // 首字母数组
      letterArr: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '#'],
      flag: true,
      newArr: [],
      result: true,
      isRefreshing: false,
      datalist: [],
      list: [],
      length: 0,
      IntroduceList: [],
      occupationLabels: [],
      Selfdisplay: ''
    };
  }

  async componentDidMount() {
    Loading.show()
    this.getUserMaillist()
    this.getUserNewfriend()
  };


  async getUserMaillist() {
    const res = await fetchWebApi(GET_USER_MAILLIST, { token: await getStorageValue(Constant.TOKEN) }, 'GET');
    console.log("########## getUserMaillist");
    console.log(res.data[0]);

    if (res.status == 200) {
      this.setState({
        DATA: res.data,//.slice(0, 3)
      });
      // 根据首字母分组
      let sections2 = []
      var sections3 = []
      this.state.letterArr.map((item) => {
        sections2.push({
          title: item,
          datalist: [],
        })
      })


      // 根据首字母添加数据
      this.state.DATA.map((item, index) => {
        // 判断备注是否为空
        item.nickName = item.remarksName != null ? item.remarksName : item.nickName
        sections2.map((item2, index2) => {
          var str = pinyin(item.nickName, {
            heteronym: true,
            style: pinyin.STYLE_FIRST_LETTER
          })[0][0].toUpperCase()
          if (item2.title == str[0]) {
            // 判断名字拼音是否相同，相同push到相对应的数组下
            item2.datalist.push({
              data: item
            })
            // 判断昵称是否是以数字开头
          } else if (item2.title == '#') {
            if (item.nickName == str) {
              item2.datalist.push({
                data: item
              })
            }
          }
        })
      })

      // 判断那些字母数组里面没有数据就不显示
      sections2.map((item) => {
        if (item.datalist == '') {
        } else {
          // 首字母和分组字母一样就push到数组里面
          sections3.push({
            list: item
          })
        }
      })
      this.setState({
        sections: sections3,
      })
      Loading.hide()
    } else if (res.status === 401) {
      console.log(res.status);
      await AsyncStorage.removeItem(Constant.TOKEN);
      this.props.navigation.push('Accountlogin')
    }

  }
  async getUserNewfriend() {
    const res = await fetchWebApi(GET_USER_NEWFRIENDS, { token: await getStorageValue(Constant.TOKEN) }, 'GET');
    // console.log('########## getUserNewfriend');
    // console.log(res);
    if (res.status == 200) {
      this.setState({
        datalist: res.data,
        list: []
      })
      this.state.datalist.map(item => {
        if (item.flag == 0) {
          this.state.list.push(item)
          this.state.list.map((item2, index2) => {
            if (item2.flag != 0) {
              this.state.list.splice(index2, 1)
            }
          })
        }
        this.setState({
          length: this.state.list.length
        })
      })
    }
  }
  // 判断诚信等级
  reputation() {
    this.state.DATA.map((item, index) => {
      this.reputations(item)

    })
  }
  reputations(item) {
    return (
      parseInt(item.creditLevel) == 1 ?
        <>
          <Text style={{ color: '#FDE400' }}>★</Text>
          <Text style={{ color: '#C4C4C4' }}>★</Text>
          <Text style={{ color: '#C4C4C4' }}>★</Text>
          <Text style={{ color: '#C4C4C4' }}>★</Text>
          <Text style={{ color: '#C4C4C4' }}>★</Text>
        </> : parseInt(item.creditLevel) == 2 ?
          <>
            <Text style={{ color: '#FDE400' }}>★</Text>
            <Text style={{ color: '#FDE400' }}>★</Text>
            <Text style={{ color: '#C4C4C4' }}>★</Text>
            <Text style={{ color: '#C4C4C4' }}>★</Text>
            <Text style={{ color: '#C4C4C4' }}>★</Text>
          </> : parseInt(item.creditLevel) == 3 ?
            <>
              <Text style={{ color: '#FDE400' }}>★</Text>
              <Text style={{ color: '#FDE400' }}>★</Text>
              <Text style={{ color: '#FDE400' }}>★</Text>
              <Text style={{ color: '#C4C4C4' }}>★</Text>
              <Text style={{ color: '#C4C4C4' }}>★</Text>
            </> : parseInt(item.creditLevel) == 4 ?
              <>
                <Text style={{ color: '#FDE400' }}>★</Text>
                <Text style={{ color: '#FDE400' }}>★</Text>
                <Text style={{ color: '#FDE400' }}>★</Text>
                <Text style={{ color: '#FDE400' }}>★</Text>
                <Text style={{ color: '#C4C4C4' }}>★</Text>
              </> : parseInt(item.creditLevel) == 5 ?
                <>
                  <Text style={{ color: '#FDE400' }}>★</Text>
                  <Text style={{ color: '#FDE400' }}>★</Text>
                  <Text style={{ color: '#FDE400' }}>★</Text>
                  <Text style={{ color: '#FDE400' }}>★</Text>
                  <Text style={{ color: '#FDE400' }}>★</Text>
                </> : parseInt(item.creditLevel) == 0 ?
                  <>
                    <Text style={{ color: '#C4C4C4' }}>★</Text>
                    <Text style={{ color: '#C4C4C4' }}>★</Text>
                    <Text style={{ color: '#C4C4C4' }}>★</Text>
                    <Text style={{ color: '#C4C4C4' }}>★</Text>
                    <Text style={{ color: '#C4C4C4' }}>★</Text>
                  </> : null
    )
  }

  // 失去焦点关闭键盘
  onBlurHandle = () => {
    Keyboard.dismiss();
  }


  // 根据姓名搜索好友
  onChangeTexts(value) {
    var values = Array.from(value)
    if (values == "") {
      this.setState({
        flag: true,
        newArr: []
      })
    } else {
      this.state.DATA.map((item) => {
        // 把名字分成数组
        var nickName = Array.from(item.nickName)
        values.map(item2 => {
          nickName.map(items => {
            // 判断输入的值和用户姓名
            if (item2 == items) {
              this.state.arr.push(item)
              // 数组去重
              var newArr = [...new Set(this.state.arr)]
              this.setState({
                newArr: newArr
              })
              this.setState({
                result: true
              })
            } else if (this.state.arr == '') {
              this.setState({
                result: false
              })
            }
          })
        })
      })
      this.setState({
        flag: false
      })
    }
  }

  // 根据是否有备注改变名称
  remarks(item) {
    if (item.data.remarksName == null) {
      return (
        item.data.nickName
      )
    } else {
      return (
        item.data.remarksName
      )
    }
  }
  remarks2(item) {
    if (item.remarksName == null) {
      return (
        item.nickName
      )
    } else {
      return (
        item.remarksName
      )
    }
  }

  genIndicator() {
    return (
      <View style={styles.indicatorContainer}>
        <ActivityIndicator
          style={styles.indicator}
          size='large'
          animating={true}
        />             <Text>正在加载更多</Text>
      </View>
    )
  }

  handleRefresh = () => {
    this.setState({
      isRefreshing: true,//tag,下拉刷新中，加载完全，就设置成flase
      Data: [],
      length: 0
    });
    this.getUserMaillist()
    this.getUserNewfriend()
    this.setState({
      isRefreshing: false
    })
  }
  hobby(item) {
    return (
      <View style={styles.hobby2}>
        {/* 判断会员更改图标 */}
        <Image style={styles.img} source={require('../../assets/images/introduces/hobby2.png')
        } />
        <Text style={styles.information_text0}>
          爱好：{item.hobby == null ? '用户暂未添加爱好~' : item.hobby + ''}
        </Text>
      </View>
    )
  }
  phone(item) {
    return (
      <View style={styles.hobby2}>
        {/* 判断会员更改图标 */}
        <Image style={styles.img} source={require('../../assets/images/introduces/phone2.png')
        } />
        <Text style={styles.information_text0}>
          电话：{item.phone == null ? '用户未添加手机号码~' : item.phone}
        </Text>
      </View>
    )
  }

  content(item, index2) {
    return (
      <TouchableOpacity onPress={() => {
        this.props.navigation.navigate('introduces', {
          id: item.data.friendId,
          refresh: () => {
            this.getUserMaillist()
          },
          remarksName: item.data.nickName
        });
      }}
        style={{ marginTop: 10 }}>
        <ImageBackground
          key={index2}
          source={null}
          style={styles.jianjie}
          imageStyle={{ borderRadius: 12 }}>
          <View style={{ flexDirection: 'row', display: 'flex', }}>
            <TouchableOpacity onPress={() => {
              this.props.navigation.push('friendAvatar', {
                friendAvatar: [{ url: item.data.avatar }]
              })
            }} style={styles.tops}>
              <ImageBackground source={{ uri: item.data.avatar }} imageStyle={{ borderRadius: 5 }} style={styles.tongxiang}>
              </ImageBackground>
            </TouchableOpacity>
            {/* 展示个人信息 */}
            <View style={styles.contents}>
              <View style={styles.introduce}>
                <View style={styles.introduce_content}>
                  <View style={styles.content_view}>
                    <Text numberOfLines={1} ellipsizeMode={'tail'} style={styles.introduce_text0}>
                      {this.remarks(item)}
                    </Text>
                    {item.data.userType == 0 ? this.sex(item.data.sex) : <>
                      <Image style={{ width: 18, height: 18, marginLeft: 5 }} source={require('../../assets/images/maillist/enterprise.png')} />
                    </>}
                  </View>
                </View>
              </View>
              <View style={styles.information}>
                {/* 职业 */}
                <View style={styles.occupation}>
                  <Image style={styles.img} source={require('../../assets/images/introduces/occupation2.png')} />
                  <Text style={styles.information_text0}>
                    职业：{item.data.occupation == null ? '用户未设置职业~' : item.data.occupation}
                  </Text>
                </View>
                {/* 诚信 */}
                <View style={styles.reputation}>
                  <Image style={styles.img} source={require('../../assets/images/introduces/reputation2.png')
                  } />
                  <Text style={styles.information_text0}>诚信：</Text>
                  <Text style={styles.information_text4}>
                    {this.reputations(item.data)}
                  </Text>
                </View>
                {/* 爱好 */}
                {item.data.showIndex == 0 ? this.hobby(item.data) : this.phone(item.data)}
                {/* 格言 */}
                <View style={styles.hobby2}>
                  <Image style={[styles.img, { width: 17, height: 17, marginLeft: 2 }]} source={require('../../assets/images/introduces/motto2.png')} />
                  <Text numberOfLines={1} ellipsizeMode={'tail'} style={[styles.information_text3, { marginLeft: 6 }]}>
                    格言：{item.data.motto != null ? item.data.motto : '用户很懒，什么都没写~'}
                  </Text>
                </View>

                <View style={styles.label}>
                  {
                    item.data.occupationLabel.map((item, index) => {
                      return (
                        // 根据会员改变样式
                        <View key={index} style={styles.label_box}>
                          <Text style={styles.label_text}>{item}</Text>
                        </View>
                      );
                    })
                  }
                </View>
              </View>
            </View>
          </View>
        </ImageBackground>
      </TouchableOpacity>

    )
  }
  content2(item, index2) {
    return (
      <TouchableOpacity onPress={() => {
        this.props.navigation.navigate('introduces', {
          id: item.friendId,
          refresh: () => {
            this.getUserMaillist()
          },
          remarksName: item.nickName
        });
      }}
        style={{ padding: 15 }}>
        <ImageBackground
          key={index2}
          source={null}
          style={styles.jianjie}
          imageStyle={{ borderRadius: 12 }}>
          <View style={{ flexDirection: 'row', display: 'flex', }}>
            <TouchableOpacity onPress={() => {
              this.props.navigation.push('friendAvatar', {
                friendAvatar: [{ url: item.avatar }]
              })
            }} style={styles.tops}>
              <ImageBackground source={{ uri: item.avatar }} imageStyle={{ borderRadius: 5 }} style={styles.tongxiang}>
              </ImageBackground>
            </TouchableOpacity>
            {/* 展示个人信息 */}
            <View style={styles.contents}>
              <View style={styles.introduce}>
                <View style={styles.introduce_content}>
                  <View style={styles.content_view}>
                    <Text numberOfLines={1} ellipsizeMode={'tail'} style={styles.introduce_text0}>
                      {this.remarks2(item)}
                    </Text>
                    {this.sex(item.sex)}
                  </View>
                </View>
              </View>
              <View style={styles.information}>
                {/* 职业 */}
                <View style={styles.occupation}>
                  <Image style={styles.img} source={require('../../assets/images/introduces/occupation2.png')} />
                  <Text style={styles.information_text0}>
                    职业：{item.occupation == null ? '用户未设置职业~' : item.occupation}
                  </Text>
                </View>
                {/* 诚信 */}
                <View style={styles.reputation}>
                  <Image style={styles.img} source={require('../../assets/images/introduces/reputation2.png')
                  } />
                  <Text style={styles.information_text0}>诚信：</Text>
                  <Text style={styles.information_text4}>
                    {this.reputations(item)}
                  </Text>
                </View>
                {/* 爱好 */}
                {item.showIndex == 0 ? this.hobby(item) : this.phone(item)}
                {/* 格言 */}
                <View style={styles.hobby2}>
                  <Image style={[styles.img, { width: 17, height: 17, marginLeft: 2 }]} source={require('../../assets/images/introduces/motto2.png')} />
                  <Text numberOfLines={1} ellipsizeMode={'tail'} style={[styles.information_text3, { marginLeft: 6 }]}>
                    格言：{item.motto != null ? item.motto : '用户很懒，什么都没写~'}
                  </Text>
                </View>

                <View style={styles.label}>
                  {
                    item.occupationLabel.map((item, index) => {
                      return (
                        // 根据会员改变样式
                        <View key={index} style={styles.label_box}>
                          <Text style={styles.label_text}>{item}</Text>
                        </View>
                      );
                    })
                  }
                </View>
              </View>
            </View>
          </View>
        </ImageBackground>
      </TouchableOpacity>
    )
  }

  // 判断性别
  sex(sex) {
    return (
      sex == '男' ? <Image
        style={styles.introduce_img}
        source={Images.Frame2}
      /> : null ||
        sex == '女' ? <Image
        style={styles.introduce_img}
        source={Images.Frame3}
      /> : null || sex == '' == null ? null : null
    )
  }

  render() {
    const Item = ({ item }) => {
      return (
        <View>
          <View style={styles.body_fenzu}>
            <Text style={styles.fenzu_titles}>{item.list.title}</Text>
          </View>
          <View style={{ padding: 15, }}>
            {
              item.list.datalist.map((item, index2) => {
                return (
                  <>
                    {this.content(item, index2)}
                  </>
                )
              })
            }
          </View>
        </View>
      )
    }

    // 搜索展示列表
    let newArrs = this.state.result ?
      <>
        {

          this.state.newArr.map((item, index2) => {
            return (
              <>
                {this.content2(item, index2)}
              </>
            )
          })
        }
      </> :
      <>
        <View style={styles.result}>
          <Text style={styles.result_text}>未查到此用户~</Text>
        </View>
      </>
    let result = <>
      <View style={styles.result}>
        <Text style={styles.result_text}>该用户暂无好友，请添加~</Text>
      </View>
    </>
    // 显示搜索前后页面
    let lists = this.state.flag ?
      <>
        <FlatList
          // ItemSeparatorComponent={this.space}
          showsVerticalScrollIndicator={false}
          ListHeaderComponent={
            <View style={styles.bodys}>

            </View>
          }
          data={this.state.sections}
          renderItem={Item}
          keyExtractor={(item, index) => item.id}
          ListEmptyComponent={() => {
            return (
              <>{result}</>
            )
          }}
          refreshControl={
            <RefreshControl
              refreshing={this.state.isRefreshing}
              onRefresh={this.handleRefresh.bind(this)}//因为涉及到this.state
              colors={['#ff0000', '#00ff00', '#0000ff', '#3ad564']}
              progressBackgroundColor="#ffffff"
            />
          }
          initialNumToRender={6}
        />
      </> :
      <>
        {newArrs}
      </>
    let request = <>
      <View style={styles.request}>
        <Text style={styles.request_text}>{this.state.length}</Text>
      </View>
    </>
    // 搜索结果
    return (
      <View style={{ flex: 1 }}>
        <NavBar
          navigation={this.props.navigation}
          title={'雇佣军'}
          rightImage={Images.Add}
          right={this.state.length == 0 ? null : request}
          pressRight={() => {
            this.props.navigation.push('newfriends', {
              refresh: () => {
                this.getUserMaillist()
                this.getUserNewfriend()
              }
            });
          }}
          hideLeftArrow={false}
        />
        <Loading />
        {/* 搜索框 */}
        <View style={styles.bodys_input}>
          <TextInput
            style={styles.inputs}
            inlineImageLeft="sou"
            placeholder="请输入用户名字"
            placeholderTextColor="#00000069"
            inlineImagePadding={40}
            onChange={(value) => {
              this.onChangeTexts(value.nativeEvent.text)
            }}
            onChangeText={(value) => {
              if (value == '') {
                this.setState({
                  flag: true
                })
              }
              this.setState({
                arr: []
              })
            }}
            onBlur={() => {
              this.onBlurHandle()
            }}
          />
        </View>
        <View style={{ flex: 1 }}>
          {lists}
        </View>

      </View>
    );
  }
}
const styles = StyleSheet.create({
  container: {
    display: 'flex',
    flexDirection: 'row',
    alignItems: 'center',
    height: 32,
    backgroundColor: 'transparent',
  },
  bodys: {
    backgroundColor: 'white',
  },
  bodys_input: {
    paddingLeft: 15,
    paddingRight: 15,
    backgroundColor: '#fff',
    paddingBottom: 10,
    // display: 'flex',
    // flexDirection: 'row',
    // justifyContent: 'space-between'
  },
  heards: {
    width: 395,
    display: 'flex',
    flexDirection: 'row',
    justifyContent: 'space-around',
    backgroundColor: 'white',
  },
  fontColor: {
    color: 'black',
    fontSize: 35,
  },
  inputs: {
    height: 45,
    // marginVertical: 10,
    color: 'black',
    backgroundColor: '#C4C4C440',
    borderRadius: 8,
    paddingLeft: 15,
    marginBottom: 10
  },
  top_btn: {
    width: 50,
    height: 45,
    backgroundColor: '#1890FF',
    borderRadius: 5,
    flexDirection: 'column',
    justifyContent: 'center'
  },
  btn_text: {
    textAlign: 'center',
    textAlignVertical: 'center',
    includeFontPadding: false,
    color: '#fff'
  },
  body_list: {
    display: 'flex',
    flexDirection: 'row',
    padding: 10,
    justifyContent: 'space-between',
    marginTop: 10
    // borderBottomWidth: 1,
    // borderBottomColor: '#f2f2f2',
  },
  lists: {
    color: 'black',
    fontSize: 18,
  },
  body_fenzu: {
    backgroundColor: '#C4C4C424',
    paddingLeft: 10,
    padding: 5,
  },
  fenzu_titles: {
    color: 'rgba(0, 0, 0, 0.32)',
  },
  body_data: {
    display: 'flex',
    flexDirection: 'row',
    paddingLeft: 5,
    padding: 12,
    justifyContent: 'space-between',
    backgroundColor: '#fff'
  },
  data_view: {
    display: 'flex',
    flexDirection: 'row',
    marginTop: 5
  },
  data_view2: {
    display: 'flex',
    flexDirection: 'row',
  },
  data_list: {
    color: 'black',
    paddingLeft: 10,
    fontSize: 18,
    maxWidth: 230
  },
  data_list2: {
    color: 'black',
    paddingLeft: 10,
    fontSize: 14,
    marginVertical: 5
  },
  pingjia: {
    display: 'flex',
    flexDirection: 'row',
  },
  result: {
    padding: 30,
    flexDirection: 'column',
    justifyContent: 'center',
  },
  result_text: {
    textAlign: 'center',
    textAlignVertical: 'center',
    includeFontPadding: false,
    fontSize: 20,
    color: '#c2c2c2'
  },
  loadMore: {
    alignItems: "center"
  },
  indicator: {
    color: "red",
    margin: 10
  },
  enterprise: {
    display: 'flex',
    flexDirection: 'row'
  },
  request: {
    backgroundColor: 'red',
    borderRadius: 25,
    width: 19
  },
  request_text: {
    color: '#fff',
    textAlign: 'center',
    textAlignVertical: 'center'
  },
  jianjie: {
    backgroundColor: "#44A5FF",
    paddingTop: 25,
    paddingLeft: 25,
    paddingRight: 25,
    paddingBottom: 25,
    borderRadius: 12,
    display: 'flex',
    flexDirection: 'column',
  },
  beijing: {
    height: 250,
    width: '100%'
  },
  tops: {
    display: 'flex',
    flexDirection: 'row',
    justifyContent: 'space-between'
  },
  tops_view: {
    display: 'flex',
    flexDirection: 'column',
    position: 'absolute',
    end: 0,
  },
  topsImg: {
    display: 'flex',
    flexDirection: 'row'
  },
  tongxiang: {
    height: 140,
    width: 100,
  },
  contents: {
    marginLeft: 20
  },
  introduce: {
    display: 'flex',
    flexDirection: 'column',
    marginTop: -5
  },
  introduce_content: {
    display: 'flex',
    flexDirection: 'row',
    justifyContent: 'flex-start',
  },
  content_view: {
    display: 'flex',
    flexDirection: 'row',
    width: '83%',
    marginBottom: 5
  },
  introduce_text0: {
    fontSize: 19,
    color: 'white',
    maxWidth: 140,
    marginLeft: 3
  },
  information: {
    display: 'flex',
    flexDirection: 'column',
    justifyContent: 'space-between',
    height: 140,
    marginTop: 5
  },
  occupation: {
    display: 'flex',
    flexDirection: 'row',
  },
  information_text0: {
    marginLeft: 5,
    marginTop: 1,
    color: '#fff',
    fontSize: 11,
    alignSelf: 'center'
  },
  information_text4: {
    color: '#000',
    fontSize: 11,
    alignSelf: 'center'
  },
  information_text3: {
    marginLeft: 5,
    marginTop: 1,
    color: '#fff',
    fontSize: 11,
    width: 200,
    alignSelf: 'flex-start'
  },
  img: {
    width: 21,
    height: 21
  },
  reputation: {
    display: 'flex',
    flexDirection: 'row',
    marginTop: -10
  },
  hobby: {
    display: 'flex',
    flexDirection: 'row',
    marginLeft: 5,
    marginTop: 5
  },
  hobby2: {
    display: 'flex',
    flexDirection: 'row',
    marginTop: -10
  },
  label: {
    display: 'flex',
    flexDirection: 'row',
    marginTop: -10,
    height: 25,
  },
  label_box: {
    width: 60,
    height: 25,
    flexDirection: 'column',
    justifyContent: 'center',
    borderWidth: 1,
    borderColor: '#fff',
    marginLeft: 5,
    borderRadius: 2,
    marginTop: 5
  },
  label_text: {
    color: '#fff',
    includeFontPadding: false,
    textAlignVertical: 'center',
    textAlign: 'center',
    fontSize: 9
  },
  introduce_img: {
    width: 16,
    height: 16,
    marginTop: 5,
    marginLeft: 10
  },
});
